from django.core.cache import cache
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from modeldemo.models import BookInfo, HeroInfo
from otherdemo.models import User


def index(request):
    """Django高级。。。"""
    print("otherDemo子应用的--index函数代码...")
    return HttpResponse("Django高级-主页面")


def detail(request):
    """Django高级。。。"""
    print("otherDemo子应用的--detail...")
    return HttpResponse("Django高级-详情页面")


def list(request):
    """Django高级。。。"""
    print("otherDemo子应用的--list...")
    return HttpResponse("Django高级-列表页面")


# url: http://127.0.0.1:8000/otherdemo/catch_books --->cache_books
def cache_books(request):
    """缓存测试视图"""
    # 读缓存数据DJango缓存 ,有数据且有效
    books_cache = cache.get('books_cache')
    if books_cache:
        print("从缓存读取数据")
        return HttpResponse(books_cache)
    else:
        print("从数据库或者文件读取数据")
        books_cache = BookInfo.objects.all()
        # 写数据到缓存
        cache.set('books_cache', books_cache)
        return HttpResponse(books_cache)


# url: http://127.0.0.1:8000/otherdemo/catch_heros --->catch_heros
def catch_heros(request):
    """缓存测试视图"""
    # 读缓存数据DJango缓存 ,有数据且有效
    catch_heros = cache.get('catch_heros')
    if catch_heros:
        print("从缓存读取数据")
        return HttpResponse(catch_heros)
    else:
        print("从数据库读取数据")
        catch_heros = HeroInfo.objects.all()
        # 写数据到缓存
        cache.set('catch_heros', catch_heros)
        return HttpResponse(catch_heros)


def regist(request):
    """注册视图"""
    if request.method == 'GET':
        return render(request, 'ajax_register.html')
    elif request.method == 'POST':
        info = request.POST
        username = info.get('uname')
        password = info.get('upwd')
        # 写入数据库
        User.objects.create(username=username, password=password)
        print(username, password)
        return HttpResponse("注册成功")


def check_name(request):
    """检查注册用户是否重名"""
    name = request.POST.get('uname')  # 接收前端传过来的用户名，去数据库中查找，没找到说明是可以注册 的。
    print("后台 测试 重名:",name)
    s_name = User.objects.filter(username=name)
    if s_name:  # 返回json数据，0表示用户名已存在，1表示可以注册
        return JsonResponse({"success": 0})
    else:
        return JsonResponse({"success": 1})
